<template>
  <div class="case-manage-container">
    <el-row :gutter="10" class="page-header">
      <el-col>
        <h2>接口用例管理</h2>
      </el-col>
      <el-col :align="`right`">
        <el-button type="primary" size="small" @click="openAddDialog">
          <el-icon><Plus /></el-icon> 新增用例
        </el-button>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-form :model="searchForm" class="search-form" inline>
      <el-form-item label="用例名称">
        <el-input v-model="searchForm.case_name" placeholder="请输入用例名称" size="small" />
      </el-form-item>
      <el-form-item label="请求方式">
        <el-select v-model="searchForm.method" placeholder="请选择" size="small">
          <el-option label="全部" value="" />
          <el-option label="GET" value="GET" />
          <el-option label="POST" value="POST" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="getCaseList">搜索</el-button>
        <el-button type="default" size="small" @click="resetSearch" style="margin-left: 10px">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 用例表格 -->
    <el-table
      v-loading="loading"
      :data="caseList"
      border
      stripe
      size="small"
      style="width: 100%; margin-top: 10px"
    >
      <el-table-column prop="id" label="用例ID" width="80" align="center" />
      <el-table-column prop="case_name" label="用例名称" align="center" />
      <el-table-column prop="api_url" label="接口URL" align="center" />
      <el-table-column prop="method" label="请求方式" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.method === 'GET' ? 'info' : 'primary'">
            {{ scope.row.method }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="expected_result" label="预期结果" align="center" width="200" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button type="text" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" text-color="#f56c6c" @click="deleteCase(scope.row.id)">删除</el-button>
          <el-button type="text" size="small" text-color="#4361ee" @click="runCase(scope.row.id)">执行</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 50]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 15px; text-align: right"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑用例' : '新增用例'"
      width="600px"
    >
      <el-form
        ref="caseFormRef"
        :model="caseForm"
        :rules="caseRules"
        label-width="120px"
      >
        <el-form-item label="用例名称" prop="case_name">
          <el-input v-model="caseForm.case_name" placeholder="请输入用例名称" />
        </el-form-item>
        <el-form-item label="接口URL" prop="api_url">
          <el-input v-model="caseForm.api_url" placeholder="请输入完整接口URL（如 http://xxx/api/login/）" />
        </el-form-item>
        <el-form-item label="请求方式" prop="method">
          <el-select v-model="caseForm.method" placeholder="请选择">
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
          </el-select>
        </el-form-item>
        <el-form-item label="请求参数" prop="params">
          <el-input
            v-model="caseForm.params"
            type="textarea"
            rows="4"
            placeholder="JSON格式，如 {&quot;username&quot;: &quot;admin&quot;, &quot;password&quot;: &quot;123456&quot;}"
          />
          <div class="param-tip">
            <span class="text-gray-500 text-sm">
              说明：1. GET请求填查询参数，POST请求填Body参数；2. 键值对需用双引号包裹；3. 数组格式如 {&quot;ids&quot;: [1,2,3]}
            </span>
          </div>
        </el-form-item>
        <el-form-item label="预期结果" prop="expected_result">
          <el-input
            v-model="caseForm.expected_result"
            type="textarea"
            rows="3"
            placeholder="请输入预期结果（如 状态码200、包含字段 token）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/api/request'

// 表格数据
const caseList = ref([])
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  case_name: '',
  method: ''
})

// 弹窗表单
const dialogVisible = ref(false)
const isEdit = ref(false)
const caseFormRef = ref(null)
const caseForm = reactive({
  id: '',
  case_name: '',
  api_url: '',
  method: 'GET',
  params: '',
  expected_result: ''
})

const caseRules = reactive({
  case_name: [{ required: true, message: '请输入用例名称', trigger: 'blur' }],
  api_url: [{ required: true, message: '请输入接口URL', trigger: 'blur' }],
  method: [{ required: true, message: '请选择请求方式', trigger: 'change' }],
  expected_result: [{ required: true, message: '请输入预期结果', trigger: 'blur' }]
})

// 初始化：获取用例列表
onMounted(() => {
  getCaseList()
})

// 获取用例列表（对接Django接口）
const getCaseList = async () => {
  loading.value = true
  try {
    const res = await request.get('/api/case/list/', {
      params: {
        page,
        limit,
        case_name: searchForm.case_name,
        method: searchForm.method
      }
    })
    caseList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取用例列表失败')
  } finally {
    loading.value = false
  }
}

// 打开新增弹窗
const openAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 打开编辑弹窗
const openEditDialog = (row) => {
  isEdit.value = true
  // 深拷贝行数据到表单
  for (const key in row) {
    caseForm[key] = JSON.parse(JSON.stringify(row[key]))
  }
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  caseForm.id = ''
  caseForm.case_name = ''
  caseForm.api_url = ''
  caseForm.method = 'GET'
  caseForm.params = ''
  caseForm.expected_result = ''
  if (caseFormRef.value) {
    caseFormRef.value.resetFields()
  }
}

// 提交表单（新增/编辑）
const submitForm = async () => {
  const valid = await caseFormRef.value.validate()
  if (!valid) return

  try {
    if (isEdit.value) {
      // 编辑用例
      await request.put(`/api/case/${caseForm.id}/`, caseForm)
      ElMessage.success('编辑成功！')
    } else {
      // 新增用例
      await request.post('/api/case/', caseForm)
      ElMessage.success('新增成功！')
    }
    dialogVisible.value = false
    getCaseList() // 刷新列表
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}

// 删除用例
const deleteCase = (id) => {
  ElMessageBox.confirm(
    '确认删除该用例吗？删除后不可恢复',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/api/case/${id}/`)
      ElMessage.success('删除成功！')
      getCaseList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 执行用例
const runCase = async (id) => {
  try {
    await request.post(`/api/case/${id}/run/`)
    ElMessage.success('用例执行中，请查看日志！')
  } catch (error) {
    ElMessage.error('执行失败，请检查用例配置')
  }
}

// 分页方法
const handleSizeChange = (val) => {
  limit.value = val
  getCaseList()
}

const handleCurrentChange = (val) => {
  page.value = val
  getCaseList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.case_name = ''
  searchForm.method = ''
  getCaseList()
}
</script>

<style scoped lang="scss">
.case-manage-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 15px;
  h2 {
    margin: 0;
  }
}

.search-form {
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.param-tip {
  margin-top: 8px;
  .text-gray-500 {
    color: #909399;
  }
}
</style>